const fs = require('fs')
const path = require('path')
const { readdir, lstat, unlink, rmdir } = require('fs').promises;
const compressing = require('compressing');

const argv = process.argv.splice(2)
const appId = argv[0]

const parentBuild = path.resolve(__dirname, 'build')
if (!fs.existsSync(parentBuild)) {
    // console.log(`文件夹不存在`)
    fs.mkdirSync(parentBuild)
}

async function buildStart () {
    await buildPkg('10000001').then(()=>{
        console.log('10000001 Finished')
    })
    await buildPkg('10000002').then(()=>{
        console.log('10000002 Finished')
    })
    await buildPkg('10000003').then(()=>{
        console.log('10000003 Finished')
    })
    await buildPkg('10000004').then(()=>{
        console.log('10000004 Finished')
    })
    await buildPkg('10000005').then(()=>{
        console.log('10000005 Finished')
        lastZip(parentBuild).then(()=>{
            console.log('🌺🌺🌺  >>> 整体上传文件已打包已完成')
        })
    })
}

async function lastZip (pkg) {
    compressing.zip.compressDir(parentBuild, `offline.zip`).then(async () => {
        //4.删除构建目录
        await deleteFolderAsync(parentBuild);
    })
}

async function buildPkg(appId) {
    //1.创建文件夹
    const buildDir = path.resolve(parentBuild, appId)
    if (!fs.existsSync(buildDir)) {
        fs.mkdirSync(buildDir)
    }
    //2.移动网页文件
    if (appId === '10000001') {
        fs.copyFileSync('cclx_home.html', `${buildDir}/index.html`)
    } else if (appId === '10000002') {
        fs.copyFileSync('cclx_im.html', `${buildDir}/index.html`)
    } else if (appId === '10000003') {
        fs.copyFileSync('cclx_order.html', `${buildDir}/index.html`)
    } else if (appId === '10000004') {
        fs.copyFileSync('cclx_bbs.html', `${buildDir}/index.html`)
    } else if (appId === '10000005') {
        fs.copyFileSync('cclx_my.html', `${buildDir}/index.html`)
    }

    //3.压缩
    return compressing.zip.compressDir(buildDir, `${parentBuild}/${appId}.zip`).then(async () => {
        //4.删除构建目录
        await deleteFolderAsync(buildDir)
    })
}

async function deleteFolderAsync(folderPath) {
    try {
        const files = await readdir(folderPath);

        for (const file of files) {
            const filePath = path.join(folderPath, file);
            const stats = await lstat(filePath);

            if (stats.isDirectory()) {
                // 如果是目录，递归删除
                await deleteFolderAsync(filePath);
            } else {
                // 如果是文件，直接删除
                await unlink(filePath);
            }
        }

        // 删除空文件夹
        await rmdir(folderPath);
        // console.log('文件夹已成功删除');
    } catch (error) {
        console.error('删除文件夹时出错:', error);
    }
}

// ------- 开始一键打包
buildStart()
